package com.wy.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wy.controller.dto.DiagnosisDto;
import com.wy.entity.*;
import com.wy.service.*;
import com.wy.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

import com.wy.common.R;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 王昭贵
 * @since 2023-03-22
 */
@Slf4j
@RestController
@RequestMapping("/diagnosis")
public class DiagnosisController {

    @Resource
    private IDiagnosisService diagnosisService;

    @Resource
    private IReserveService reserveService;

    @Resource
    private ICustomerService customerService;

    @Resource
    private IPetService petService;

    @Resource
    private IUserService userService;

    @Resource
    private IPetAuxiliaryCheckService petAuxiliaryCheckService;

    @Resource
    private IAuxiliaryCheckService auxiliaryCheckService;

    @Resource
    private IOrderService orderService;

    @Resource
    private IOrderDetailService orderDetailService;

    @Resource
    private IPetDrugService petDrugService;

    @Resource
    private IDrugService drugService;

    /****
     * 复诊页面接口，根据问诊记录复诊
     * @param diagnosisDto
     * @return
     */
    @Transactional
    @PostMapping("/updatereview")
    public R updateReviewTreat(@RequestBody DiagnosisDto diagnosisDto){
        Diagnosis diagnosis = diagnosisService.getById(diagnosisDto.getId());
        diagnosis.setTreatmentPlan(diagnosisDto.getTreatmentPlan());
        diagnosis.setDoctorTell(diagnosisDto.getDoctorTell());
        diagnosis.setStatus(2);//将问诊信息状态置为2 表示已就诊完毕
        diagnosisService.updateById(diagnosis);
        double sumPrice = 0.0;
        int[] drugArr = diagnosisDto.getDrugArr();
        //1.生成订单--订单表--药物
        for (int i = 0; i < drugArr.length; i++) {
            sumPrice += drugService.getById(drugArr[i]).getPrice();
        }
        Order order = new Order();
        order.setCode(CommonUtils.customFormatDate("yyyyMMddHHmmssSSSSSSS"));
        order.setCustomerId(diagnosis.getCustomerId());
        order.setDiagnosisId(diagnosis.getId());
        order.setPayType(0);
        order.setPayPrice(BigDecimal.valueOf(sumPrice));
        order.setPayStatus(0);
        orderService.save(order);
        //2.订单明细
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(order.getId());
        orderDetail.setSourceType(1);
        orderDetail.setCount(1);//暂时设定药品默认数量为1
        for (int i = 0; i < drugArr.length; i++) {
            orderDetail.setSourceId(drugArr[i]);
            orderDetail.setSinglePrice(drugService.getById(drugArr[i]).getPrice());
            orderDetailService.save(orderDetail);
        }
        //3.添加数据--药物明细表
        PetDrug petDrug = new PetDrug();
        petDrug.setCustomerId(diagnosisDto.getCustomerId());
        petDrug.setPetId(diagnosisDto.getPetId());
        petDrug.setDiagnosisId(diagnosis.getId());
        petDrug.setOrderId(order.getId());
        petDrug.setStatus(0);
        for (int i = 0; i < drugArr.length; i++) {
            petDrug.setDrugId(drugArr[i]);
            petDrugService.save(petDrug);
        }
        return R.success("复诊成功");
    }

    /****
     * 预约界面--开始问诊
     * @param diagnosisDto
     * @return
     */
    @Transactional
    @PostMapping
    public R save(@RequestBody DiagnosisDto diagnosisDto) {
        Reserve reserve = reserveService.getById(diagnosisDto.getReserveId());
        reserve.setTreateStatus(1);//修改预约状态 置为1表示已就诊
        reserveService.saveOrUpdate(reserve);
        Diagnosis diagnosis = new Diagnosis();//将预约信息转为问诊信息存储
        diagnosis.setPetId(diagnosisDto.getPetId());
        diagnosis.setReserveId(diagnosisDto.getReserveId());
        diagnosis.setCustomerId(diagnosisDto.getCustomerId());
        diagnosis.setDiseaseAnalysis(diagnosisDto.getDiseaseAnalysis());
        diagnosis.setTreatmentPlan(diagnosisDto.getTreatmentPlan());
        //问诊页面 若有检查则先做检查，没检查直接药物处理
        diagnosis.setUserId(reserveService.getById(diagnosisDto.getReserveId()).getUserId());
        //是否有辅助检查
        if (diagnosisDto.getAuxiliaryArr().length == 0) {
            //当前不需要做检查
            diagnosis.setStatus(2);
            diagnosis.setDiseaseAnalysis(diagnosisDto.getDiseaseAnalysis());
            diagnosis.setTreatmentPlan(diagnosisDto.getTreatmentPlan());
            diagnosis.setDoctorTell(diagnosisDto.getDoctorTell());
            diagnosisService.save(diagnosis);
            double sumPrice = 0.0;
            int[] drugArr = diagnosisDto.getDrugArr();
            //1.生成订单--订单表--药品
            for (int i = 0; i < drugArr.length; i++) {
                sumPrice += drugService.getById(drugArr[i]).getPrice();
            }
            Order order = new Order();
            order.setCode(CommonUtils.customFormatDate("yyyyMMddHHmmssSSSSSSS"));
            order.setCustomerId(diagnosis.getCustomerId());
            order.setDiagnosisId(diagnosis.getId());
            order.setPayType(0);
            order.setPayPrice(BigDecimal.valueOf(sumPrice));
            order.setPayStatus(0);
            orderService.save(order);
            //2.订单明细
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(order.getId());
            orderDetail.setSourceType(1);
            orderDetail.setCount(1);//暂时设定药品默认数量为1
            for (int i = 0; i < drugArr.length; i++) {
                orderDetail.setSourceId(drugArr[i]);
                orderDetail.setSinglePrice(drugService.getById(drugArr[i]).getPrice());
                orderDetailService.save(orderDetail);
            }
            //3.添加数据--药物明细表
            PetDrug petDrug = new PetDrug();
            petDrug.setCustomerId(diagnosisDto.getCustomerId());
            petDrug.setPetId(diagnosisDto.getPetId());
            petDrug.setDiagnosisId(diagnosis.getId());
            petDrug.setOrderId(order.getId());
            petDrug.setStatus(0);
            for (int i = 0; i < drugArr.length; i++) {
                petDrug.setDrugId(drugArr[i]);
                petDrugService.save(petDrug);
            }
        } else {
            //当前需要做检查
            diagnosis.setStatus(1);
            diagnosisService.save(diagnosis);
            double sumPrice = 0;
            int[] auxiliaryArr = diagnosisDto.getAuxiliaryArr();
            //1.生成订单--订单表--辅助检查
            for (int i = 0; i < auxiliaryArr.length; i++) {
                sumPrice += auxiliaryCheckService.getById(auxiliaryArr[i]).getPrice();
            }
            Order order = new Order();
            order.setCode(CommonUtils.customFormatDate("yyyyMMddHHmmssSSSSSSS"));
            order.setCustomerId(diagnosis.getCustomerId());
            order.setDiagnosisId(diagnosis.getId());
            order.setPayType(0);
            order.setPayPrice(BigDecimal.valueOf(sumPrice));
            order.setPayStatus(0);
            orderService.save(order);
            //2.订单明细
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(order.getId());
            orderDetail.setSourceType(0);
            orderDetail.setCount(1);
            for (int i = 0; i < auxiliaryArr.length; i++) {
                orderDetail.setSourceId(auxiliaryArr[i]);
                orderDetail.setSinglePrice(auxiliaryCheckService.getById(auxiliaryArr[i]).getPrice());
                orderDetailService.save(orderDetail);
            }
            //3.添加数据--辅助检查明细表
            PetAuxiliaryCheck petAuxiliaryCheck = new PetAuxiliaryCheck();
            petAuxiliaryCheck.setCustomerId(diagnosisDto.getCustomerId());
            petAuxiliaryCheck.setPetId(diagnosisDto.getPetId());
            petAuxiliaryCheck.setDiagnosisId(diagnosis.getId());
            petAuxiliaryCheck.setOrderId(order.getId());
            petAuxiliaryCheck.setStatus(0);
            for (int i = 0; i < auxiliaryArr.length; i++) {
                petAuxiliaryCheck.setAuxiliaryCheckId(auxiliaryArr[i]);
                petAuxiliaryCheckService.save(petAuxiliaryCheck);
            }
        }
        return R.success("问诊成功");
    }

    /****
     * 复诊界面数据加载
     * @param id
     * @return
     */
    @GetMapping("/getreviewtreatinfo/{id}")
    public R getDiagnosisByIdToReviewTreat(@PathVariable Integer id){
       DiagnosisDto diagnosisDto = diagnosisService.getDiagnosisByIdToReviewTreat(id);
        return  R.success(diagnosisDto);
    }



    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id) {
        diagnosisService.removeById(id);
        return R.success("");
    }

    @PostMapping("/del/batch")
    public R deleteBatch(@RequestBody List<Integer> ids) {
        diagnosisService.removeByIds(ids);
        return R.success("");
    }

    @GetMapping
    public R findAll() {
        return R.success(diagnosisService.list());
    }

    @GetMapping("/{id}")
    public R findOne(@PathVariable Integer id) {
        return R.success(diagnosisService.getById(id));
    }

    /**
     * 前台根据用户ID查询既往病例
     */
    @GetMapping("/pageByCustomerId")
    public R findPageByCustomerId(@RequestParam int customerId, @RequestParam Integer page,
                                  @RequestParam Integer pageSize) {

        LambdaQueryWrapper<Diagnosis> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Diagnosis::getCustomerId, customerId);
        queryWrapper.orderByDesc(Diagnosis::getId);
        Page<Diagnosis> page1 = diagnosisService.page(new Page<>(page, pageSize), queryWrapper);
        page1.getRecords().stream().forEach(item -> {
            item.setPetName(petService.getById(item.getPetId()).getName());
            item.setCustomerName(customerService.getById(item.getCustomerId()).getName());
            item.setUserName(userService.getById(item.getUserId()).getNickname());
        });
        return R.success(page1);
    }

    /**
     * 管理系统 根据当前用户角色查询既往病例
     **/
    @GetMapping("/page")
    public R findPage(@RequestParam int userId, @RequestParam Integer page,
                      @RequestParam Integer pageSize,@RequestParam String name) {
        User user = userService.getById(userId);
        LambdaQueryWrapper<Diagnosis> queryWrapper = new LambdaQueryWrapper<>();
        if (!user.getRole().equals("ROLE_ADMIN")) {
            queryWrapper.eq(Diagnosis::getUserId, userId);
        }
        queryWrapper.orderByAsc(Diagnosis::getStatus);
        queryWrapper.orderByDesc(Diagnosis::getId);
        Page<Diagnosis> page1 = diagnosisService.page(new Page<>(page, pageSize), queryWrapper);
        page1.getRecords().stream().forEach(item -> {
            LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderLambdaQueryWrapper.eq(Order::getDiagnosisId,item.getId());
            List<Order> list = orderService.list(orderLambdaQueryWrapper);
            list.forEach(order->{
                if(order.getPayStatus() ==1){
                    item.setPayStatus(1);
                }else {
                    item.setPayStatus(0);
                }
            });
            item.setImage(petService.getById(item.getPetId()).getImage());
            item.setPetName(petService.getById(item.getPetId()).getName());
            item.setCustomerName(customerService.getById(item.getCustomerId()).getName());
            item.setUserName(userService.getById(item.getUserId()).getNickname());
        });
        List<Diagnosis> collect = page1.getRecords().stream().filter(item -> item.getPetName().contains(name)).collect(Collectors.toList());
        page1.setRecords(collect);
        log.info("当前数据{}", page1.getRecords());
        return R.success(page1);
    }

}

